import axios from 'axios';
import router from '../router';
// import Vue from 'vue';
import { message } from 'ant-design-vue';

// eslint-disable-next-line no-undef
export const sign = process.env.NODE_ENV === 'production' ? '' : '';

// eslint-disable-next-line no-undef
const baseURL = process.env.VUE_APP_API_BASE_URL;

const service = axios.create({
  baseURL,
  timeout: 30000
});

service.interceptors.request.use(config => {
  /* eslint-disable */
  let token = config.noToken ? '' : localStorage.getItem('token');
  if(token) {
    config.headers.Authorization  = token;
  }

  return config;
},
() => {
});

service.interceptors.response.use(response => {
  const { data, config } = response;
  if (data.status === 200) {
		// data.message && message.success(data.message);
    return data.data;
  } else {
    if(!config.noMessage) {
      message.error(data.message || 'Error');
    }

    return Promise.reject(new Error(data.error || 'Error'));
  }
},
error => {
  if (error.response.status === 401) {
    // token过期
    localStorage.removeItem('token') // 清除旧token
    message.warning('登录过期，请重新登录');
    router.push('/login');
  }else{
    message.error('服务异常');
  }

  return Promise.reject(error);
});

export default service;
